package me.yushuai.wukong.base.controller;

import me.yushuai.wukong.base.api.WorkingAreaApi;
import me.yushuai.wukong.base.api.dto.CreateWorkingAreaDTO;
import me.yushuai.wukong.base.api.dto.PagingSearchWorkingArea;
import me.yushuai.wukong.base.api.dto.UpdateWorkingAreaDTO;
import me.yushuai.wukong.base.api.dto.WorkingAreaDTO;
import me.yushuai.wukong.base.service.WorkingAreaService;
import me.yushuai.wukong.common.dto.PageDTO;
import me.yushuai.wukong.common.error.WuKongException;
import me.yushuai.wukong.common.error.WuKongWebException;
import me.yushuai.wukong.common.exceptin.BizIdNotExistException;
import me.yushuai.wukong.common.mvc.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * 工作区控制器
 *
 * @author zhoushuai@189.cn
 * @since 2022-09-07
 */
@RestController
public class WorkingAreaController extends BaseController implements WorkingAreaApi {

    public static final String WORKING_AREA_BIZ_ID_NOT_FOUND = "WorkingArea.bizId.NotFound";
    /**
     * 工作区业务类
     */
    private final WorkingAreaService workingAreaService;

    @Autowired
    public WorkingAreaController(WorkingAreaService workingAreaService) {
        this.workingAreaService = workingAreaService;
    }

    @Override
    public Long createWorkingArea(CreateWorkingAreaDTO dto) throws WuKongException {
        return this.workingAreaService.createWorkingArea(dto);
    }

    @Override
    public Long editWorkingArea(Long id, UpdateWorkingAreaDTO dto) throws WuKongException {
        dto.setId(id);
        return this.workingAreaService.updateWorkingAreaById(dto);
    }

    @Override
    public Long deleteWorkingArea(Long id) throws WuKongException {
        this.workingAreaService.deleteWorkingArea(id);
        return id;
    }

    @Override
    public WorkingAreaDTO getById(Long workingAreaId) throws WuKongException {
        return this.workingAreaService.findById(workingAreaId);
    }

    @Override
    public WorkingAreaDTO getByBizId(String workingAreaCode) throws WuKongWebException {
        try {
            return this.workingAreaService.findWorkingAreaByBizId(workingAreaCode);
        } catch (BizIdNotExistException e) {
            final Object[] params = {e.getBizId()};
            String defaultMessage = "The bizId of WorkingAre \"" + e.getBizId() + "\" is not found.";
            throw new WuKongWebException(super.messageSource.getMessage(WORKING_AREA_BIZ_ID_NOT_FOUND, params,
                    defaultMessage, super.getCurrentLocale()));
        }
    }

    @Override
    public PageDTO<WorkingAreaDTO> pagingSearchWorkingArea(PagingSearchWorkingArea dto) {
        return this.workingAreaService.pagingSearchWorkingArea(dto);
    }
}
